package cn.kt.mywxdemo.token;

import cn.kt.mywxdemo.utils.HttpUtil;
import net.sf.json.JSONObject;


/**
 * Created by tao.
 * Date: 2023/3/7 16:26
 * 描述:
 */
public class TokenUtil {

    private static final String APP_ID = "wx90a9158b6acc5584";
    private static final String APP_SECRET = "ec23a5d78f12afa569c64794570d753c";
    private static AccessToken accessToken = new AccessToken();

    public static void main(String[] args) {
        //{"access_token":"63_8R2EcPuM3dz_D81Q2FBiSfgrlwokafQloAU33iFhHIbjabRFtC_thRqk7VOkMbarQ8lA9yyq2pgwh4pc6P-5qQutc6WWMLwFafIR6ZaLkB299OJU78npFt--I0ACXCiACAHCH","expires_in":7200}
        System.out.println(getAccessToken());
    }

    private static void getToken() {
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                APP_ID,
                APP_SECRET);
        String result = HttpUtil.doGet(url);
        JSONObject jsonObject = JSONObject.fromObject(result);
        String token = jsonObject.getString("access_token");
        long expiresIn = jsonObject.getLong("expires_in");
        accessToken.setToken(token);
        accessToken.setExpireTime(expiresIn);
    }

    /**
     * 获取AccessToken
     *
     * @return
     */
    public static String getAccessToken() {
        if (accessToken == null || accessToken.isExpired()) {
            getToken();
        }
        return accessToken.getToken();
    }

}
